import cloud from '@lafjs/cloud'
let data
const db = cloud.mongo.db
let dbName = "admin-teaching-schedule-ToC"

export default async function (ctx: FunctionContext) {
  data = ctx.body.data

  switch (ctx.body.type) {
    case "add":
      return add()
      break;
    case "query":
      return scheduleList()
      break;
    case "del":
      return delFunc()
      break;
    case "update":
      return cloud.utils.updateData(dbName, data)
      break;
    default:
      break;
  }
}

//新增排课
async function add() {
  let aa = await db.collection(dbName)
    .find({ classId: data.classId, date: data.date })
    .toArray()
  for (let index = 0; index < aa.length; index++) {
    const element = aa[index];
    if (isTimeRangeOverlap(element.classStartTime, element.classEndTime, data.classStartTime, data.classEndTime)) {
      return cloud.utils.requestReturn({ msg: `${data.date} ${data.classStartTime}-${data.classEndTime}时间段与${element.classStartTime}-${element.classEndTime}时间段冲突`, code: 500 })
    }
  }
  await cloud.nw.db.add({
    dbName,
    dataJson: data,
    cancelAddTime: false
  });

  //判断之前是否有这一天
  function isTimeRangeOverlap(startTime1, endTime1, startTime2, endTime2) {
    // 将时间字符串转换为分钟数
    const convertToMinutes = (timeStr) => {
      const [hours, minutes] = timeStr.split(':').map(Number);
      return hours * 60 + minutes;
    };

    const startMinutes1 = convertToMinutes(startTime1);
    const endMinutes1 = convertToMinutes(endTime1);
    const startMinutes2 = convertToMinutes(startTime2);
    const endMinutes2 = convertToMinutes(endTime2);

    return !(endMinutes1 < startMinutes2 || startMinutes1 > endMinutes2);
  }
  return cloud.utils.requestReturn({ data: "" })
}

//删除排课
async function delFunc() {
  await cloud.nw.db.del({
    dbName,
    whereJson: { _id: data._id }
  });
  return cloud.utils.requestReturn({ data: "" })
}

//排期
async function scheduleList() {
  let list = await db.collection("admin-teaching-schedule-ToC").find(data).toArray()
  return cloud.utils.requestReturn({ data: list })
}